{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# How to solve the [Hat puzzle](https://en.wikipedia.org/wiki/Hat_puzzle#Ten-Hat_Variant) programmatically.\n",
    "> Ten-Hat Variant\n",
    "\n",
    "> In this variant there are 10 prisoners and 10 hats. Each prisoner is assigned a random hat, either red or blue, but the number of each color hat is not known to the prisoners. The prisoners will be lined up single file where each can see the hats in front of him but not behind. Starting with the prisoner in the back of the line and moving forward, they must each, in turn, say only one word which must be \"red\" or \"blue\". If the word matches their hat color they are released, if not, they are killed on the spot. A friendly guard warns them of this test one hour beforehand and tells them that they can formulate a plan where by following the stated rules, 9 of the 10 prisoners will definitely survive, and 1 has a 50/50 chance of survival. What is the plan to achieve the goal?\n",
    "\n",
    "This puzzle involves three concepts common to classic logic puzzles:\n",
    "* [Theory of mind](https://en.wikipedia.org/wiki/Theory_of_mind)\n",
    "* [Functional fixedness](https://en.wikipedia.org/wiki/Functional_fixedness)\n",
    "* [Induction](https://en.wikipedia.org/wiki/Induction_puzzles)\n",
    "\n",
    "Theory of mind comes into play because each prisoner has differing knowledge, but assumes everyone else will think similarly.  Functional fixedness occurs more subtly; each prisoner may state a color only to convey information.  But because the information is encoded as a color, it tends to focus thinking on the colors themselves.  So to combat that cognitive bias, first create a different enumeration to represent statements.  Any binary `enum` can be mapped back to colors, so why not `bool`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": "('red', 'blue')"
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "colors = 'red', 'blue'\n",
    "colors[False], colors[True]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Which leaves induction: solve the puzzle for the base case (smallest size) first, and then methodically build on that solution.  In the case of 1 prisoner, they have no information a priori, and therefore have a 50/50 chance of survival regardless of strategy.  This variant of the puzzle already gives the optimal goal, so we know that everyone but the 1st can say their color and be saved, while the 1st can devote their answer to the common cause.\n",
    "\n",
    "In the case of 2 prisoners, obviously the 1st can say the color of the 2nd.  That approach does not scale; it is the path to functional fixedness.  Instead, methodically enumerate all possible statements and colors to determine if there is an unambiguous solution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": "[(False, 'red'), (True, 'blue')]"
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "table = list(zip([False, True], colors))\n",
    "table"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The above table is a general solution with no assumptions other than the arbitrary ordering of enums.  While it may appear absurdly pedantic, it represents a rule set which is key to building a recursive solution.\n",
    "\n",
    "In the case of the 3rd prisoner, clearly they can not just repeat the above rule set, because the 3rd would receive no information.  But there are only 2 choices, so the only option is to follow the *opposite* rule set, depending on the 3rd color.\n",
    "\n",
    "The crucial step is to build off of the existing `table`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": "[(False, 'red', 'red'),\n (True, 'blue', 'red'),\n (True, 'red', 'blue'),\n (False, 'blue', 'blue')]"
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "table = [row + colors[:1] for row in table] + [(not row[0],) + row[1:] + colors[1:] for row in table]\n",
    "table"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The solution is valid if each prisoner is able to narrow the possibilities to a unique row based on the colors they hear and see."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "import collections\n",
    "\n",
    "def test(table):\n",
    "    \"\"\"Assert that the input table is a valid solution.\"\"\"\n",
    "    (size,) = set(map(len, table))\n",
    "    for index in range(size):\n",
    "        counts = collections.Counter(row[:index] + row[index + 1:] for row in table)\n",
    "        assert set(counts.values()) == {1}\n",
    "\n",
    "test(table)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The general solution is simply the above logic in recursive form, with a parametrized size."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": "[(False, 'red', 'red'),\n (True, 'red', 'blue'),\n (True, 'blue', 'red'),\n (False, 'blue', 'blue')]"
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def solve(count: int):\n",
    "    \"\"\"Generate a flat table of all spoken possibilities.\"\"\"\n",
    "    if count <= 1:\n",
    "        yield False,\n",
    "        return\n",
    "    for row in solve(count - 1):\n",
    "        yield row + colors[:1]\n",
    "        yield (not row[0],) + row[1:] + colors[1:]\n",
    "\n",
    "list(solve(3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The complicated puzzle is actually a trivial recurrence relation:\n",
    "$$\n",
    "2^n = 2^{n-1} * 2\n",
    "$$\n",
    "There are $2^n$ states of the prisoners, and each prisoner has $n-1$ bits of data.  So an additional bit of data from the first is sufficient to solve the puzzle."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": "512"
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "table = list(solve(10))\n",
    "test(table)\n",
    "len(table)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": "[(False, 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'red'),\n (True, 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'blue'),\n (True, 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'blue', 'red')]"
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "table[:3]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The puzzle is solved, but the output is of exponential size, certainly not the succinct solution which makes the puzzle famous.  But instead of relying on a flash of insight, this approach produces not just *a* solution, but *the* solution.  The only arbitrary decision made was the enumeration.  Therefore it must be the case that the solution can be summarized.\n",
    "\n",
    "First, it would be helpful to group the solution by the 1st statement.  Any summary function would have to ensure that there is no collision in the grouped possibilities."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": "(256, 256)"
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "groups = collections.defaultdict(set)\n",
    "for row in table:\n",
    "    groups[row[0]].add(row[1:])\n",
    "groups = groups[False], groups[True]\n",
    "\n",
    "def summarize(func, groups):\n",
    "    \"\"\"Apply summary function to groups and assert uniqueness.\"\"\"\n",
    "    groups = tuple(set(map(func, group)) for group in groups)\n",
    "    assert set.isdisjoint(*groups)\n",
    "    return groups\n",
    "\n",
    "assert summarize(lambda g: g, groups) == groups\n",
    "tuple(map(len, groups))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now what summaries to attempt?  Well there are few properties of sequences to work with: size and order.  They are all the same size, so that won't help.  That leaves ordering, which can be easily tested by sorting."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": "({('blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'red'),\n  ('blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'red', 'red', 'red'),\n  ('blue', 'blue', 'blue', 'blue', 'red', 'red', 'red', 'red', 'red'),\n  ('blue', 'blue', 'red', 'red', 'red', 'red', 'red', 'red', 'red'),\n  ('red', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'red')},\n {('blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue'),\n  ('blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'red', 'red'),\n  ('blue', 'blue', 'blue', 'blue', 'blue', 'red', 'red', 'red', 'red'),\n  ('blue', 'blue', 'blue', 'red', 'red', 'red', 'red', 'red', 'red'),\n  ('blue', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'red')})"
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "summarize(lambda g: tuple(sorted(g)), groups)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Success.  Now that order does not matter, the appropriate data structure is a multiset (a.k.a. bag).  Each prisoner can keep track of only how many of each color they hear and see."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": "({frozenset({('blue', 8), ('red', 1)}),\n  frozenset({('blue', 2), ('red', 7)}),\n  frozenset({('blue', 6), ('red', 3)}),\n  frozenset({('blue', 4), ('red', 5)}),\n  frozenset({('red', 9)})},\n {frozenset({('blue', 1), ('red', 8)}),\n  frozenset({('blue', 7), ('red', 2)}),\n  frozenset({('blue', 5), ('red', 4)}),\n  frozenset({('blue', 3), ('red', 6)}),\n  frozenset({('blue', 9)})})"
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "summarize(lambda g: frozenset(collections.Counter(g).items()), groups)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Since there are only 2 colors which sum to a constant, keeping track of just one is sufficient."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": "({1, 3, 5, 7, 9}, {0, 2, 4, 6, 8})"
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "summarize(lambda g: g.count(colors[0]), groups)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There's one last pattern to the numbers, which can be used to achieve [parity](https://en.wiktionary.org/wiki/parity) with the canonical solution."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "env": {},
   "interrupt_mode": "signal",
   "language": "python",
   "metadata": {},
   "name": "python3"
  },
  "nikola": {
   "category": "puzzles",
   "date": "2020-01-11",
   "description": "",
   "link": "",
   "slug": "hat-puzzle",
   "tags": "",
   "title": "Hat puzzle",
   "type": "text"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}